<?php
class Login extends CI_Controller
{	
	function __construct() {
        parent::__construct();
    }

    public $token_expiration = 300;    //配置token的有效时长user_info

    /**
     * 手机登录
     * @return [type] [description]
     */
    function login_by_phone(){
        $data = file_get_contents("php://input");
    	if(!empty($data)){
    		$data = json_decode($data, true);
        	$phone = $data['phone'];
        	$pwd = $data['password'];

        	//查用户
        	$this->load->model('Users');
        	$user = $this->Users->get_user_by_phone($phone);
        	if(empty($user)){
        		echo json_encode(array("code" => 404, "data" => 'not user'));
        		exit;
        	}

        	$password = md5(md5($pwd) . $user['rand_str']);

        	if($user['password'] != $password){
        		echo json_encode(array("code" => 401, "data" => 'password error'));
        		exit;
        	}

        	$time = time();
        	//生成用户token
        	$token = create_rand_str(32, 32);
            $token_data = array("token" => $token, "create_time" => $time, "token_expiration" => $this->token_expiration);
            $token_data['token_expiration_date'] = date("Y-m-d H:i:s", $token_data['create_time']+$token_data['token_expiration']);
            $token_info = get_field_by_where("user_tokens", "id", "user_id = '{$user['user_id']}'");

            if(!empty($token_info['id'])){
                $this->db->update("user_tokens", $token_data, array("user_id" => $user['user_id']));
            }else{
                $token_data['user_id'] = $user['user_id'];
                $this->db->insert("user_tokens", $token_data);
            }

            $child_total = get_field_by_where("user_childrens", "count(id) AS count", "user_id='{$user['user_id']}' ");
            $user['total_child'] = $child_total['count'];
            $child_info = get_field_by_where("user_childrens", "nick, head_img_url, grade, gender", "id='{$user['child_id']}'");
            if(empty($child_info['head_img_url'])){
                if($child_info['gender'] == 1){
                    $user['child_head_img_url'] = get_qiniu_url('FtE8Gn7PqWv0W7aVTuab8RcuGxlm');
                }else{
                    $user['child_head_img_url'] = get_qiniu_url('Fsof6z54HyIM401i0amzqo3VzrF3');
                }
            }else{
                $user['child_head_img_url'] = $child_info['head_img_url'];
            }
            $user['child_nick'] = $child_info['nick'];

            $token_info = array_merge($user, $token_data);
            echo json_encode(array("code" => 200, "token_info" => $token_info));
        	// $user_info = array(
        	// 	'user_id' => $user['id'], 
        	// );
         //    echo json_encode(array("code" => 0, "data" => $user_info));
        }else{
            echo json_encode(array("code" => 400, "data" => 'parameters error'));
        }
    }

    /**
     * 发送手机验证码
     * @return [type] [description]
     */
    function send_code(){
    	$data = file_get_contents("php://input");
		if(!empty($data)){
			$data = json_decode($data, true);
    		$phone = $data['phone'];

    		//查用户
        	$this->load->model('Users');
        	$user = $this->Users->get_user_by_phone($phone);
        	if(empty($user) == false){
        		echo json_encode(array("code" => 404, "data" => '您已经注册过了，请登录'));
        		exit;
        	}


        	$this->load->helper('common');
	        //查询用户最后一条code
	        $this->load->model("Verification_code_model");
	        $code_model = $this->Verification_code_model->getLastCodeByPhone($phone,1);
	        if(empty($code_model)|| strtotime($code_model['create_on'])+1*60<time()){
	            $code = getRandChar(4);
	            $result = $this->Verification_code_model->insertCodeLog($phone,$code,1);
	            if($result>0){
	                $send_result = send_verify_code_msg($phone,$code);
	  
                    if(json_decode($send_result)->code==200){
                    	echo json_encode(array("code" => 200, "data" => '发送成功'));
                       
                        exit ;
                    }else{
                    	echo json_encode(array("code" => 201, "data" => $send_result));
                        exit;
                    }
                
	                
	            }else{
	                
	                echo json_encode(array("code" => 500, "data" => '系统异常'));
	                exit ;
	            }
	        }else{
	        	echo json_encode(array("code" => 505, "data" => '您操作太频率了！请稍后'));
	            // print_r('{"code":500,"msg":"您操作太频率了！请稍后"}');
	            exit ;
	        }



		}else{
        	echo json_encode(array("code" => 400, "data" => 'parameters error'));
    	}
    }

    /**
     * 手机注册
     * @return [type] [description]
     */
    function reg_phone(){
    	$data = file_get_contents("php://input");
		if(!empty($data)){
			$data = json_decode($data, true);
    		$phone = $data['phone'];
    		$code = $data['code'];
    		$pwd = $data['password'];

    		//查用户
        	$this->load->model('Users');
        	$user = $this->Users->get_user_by_phone($phone);
        	if(empty($user) == false){
        		echo json_encode(array("code" => 404, "data" => '您已经注册过了，请登录'));
        		exit;
        	}


        	//判断验证码是否正确
            if(empty($phone)==false && empty($code)==false){
                //查询用户最后一条code
                $this->load->model("Verification_code_model");
                $code_model = $this->Verification_code_model->getLastCodeByPhone($phone,1);
                if($code_model['is_use']==1||$code_model['code']!=$code){
                    //验证码错误
                    echo json_encode(array("code" => 405, "data" => '验证码错误'));
        			exit;
                }
            }

            //添加数据
            $md5_pass = md5($pwd);
			$rand_str = '';
			for($i=0; $i<10; $i++){
				$rand_str .= substr($md5_pass, rand(0, strlen($md5_pass)-1), 1);
			}

			$password = md5($md5_pass.$rand_str);

			$user_new = array(
				'child_id' => 0, 
				'nick' => $phone, 
				'mobile' => $phone, 
				'password' => $password, 
				'sex' => 0, 
				'rand_str' => $rand_str, 
				'head_img_url' => '', 
				'child_lock' => 2, 
				'add_time' => time(), 
				'Country' => '', 
				'province' => '', 
				'reward_num' => 0, 
			);

            //添加注册
            $result = $this->db->insert('users',$user_new);
            $user_id = $this->db->insert_id();
            if($result > 0) {

                $time = time();
	        	//生成用户token
	        	$token = create_rand_str(32, 32);
	            $token_data = array("token" => $token, "create_time" => $time, "token_expiration" => $this->token_expiration);
	            $token_data['token_expiration_date'] = date("Y-m-d H:i:s", $token_data['create_time']+$token_data['token_expiration']);
	            $token_info = get_field_by_where("user_tokens", "id", "user_id = '{$user_id}'");

	            if(!empty($token_info['id'])){
	                $this->db->update("user_tokens", $token_data, array("user_id" => $user_id));
	            }else{
	                $token_data['user_id'] = $user_id;
	                $this->db->insert("user_tokens", $token_data);
	            }
	            $token_info = array_merge($user_new, $token_data);
	            echo json_encode(array("code" => 200, "token_info" => $token_info));
            	exit;
            }


        }else{
        	echo json_encode(array("code" => 400, "data" => 'parameters error'));
    	}

    }

}